import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/utils/format_utils.dart';

class QuotaController extends GetxController {
  TextEditingController quotaController = TextEditingController();
  FocusNode quotaFocus = FocusNode();
  double quota = 0.0;
  String cycleType = "";
  String cycleName = "";
  String unitType = "";
  String unitName = "";
  String beforeQuota = "";
  List<Cycle> cycleList = [];
  List<Unit> unitList = [];

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      quota = arguments[Constant.PARAM_QUOTA];
      cycleType = arguments[Constant.PARAM_QUOTA_CYCLE_TYPE];
      cycleName = arguments[Constant.PARAM_QUOTA_CYCLE_NAME];
      unitType = arguments[Constant.PARAM_QUOTA_UNIT_TYPE];
      unitName = arguments[Constant.PARAM_QUOTA_UNIT_NAME];
      if (quota > 0.0) {
        beforeQuota = "${FormatUtils.formatMoney(quota)}$unitName/$cycleName";
        quotaController.text = quota.toString();
      }
      update();
    }
  }

  void setQuota(String value) {
    if (value.isEmpty) {
      quota = 0.0;
    } else {
      quota = double.parse(value);
    }
    update();
  }

  void onConfirm() {
    if (cycleType.isEmpty || cycleType.isEmpty || quota <= 0.0) {
      return;
    }
    Get.back(result: {
      Constant.PARAM_QUOTA: quota,
      Constant.PARAM_QUOTA_CYCLE_TYPE: cycleType,
      Constant.PARAM_QUOTA_CYCLE_NAME: cycleName,
      Constant.PARAM_QUOTA_UNIT_TYPE: unitType,
      Constant.PARAM_QUOTA_UNIT_NAME: unitName,
    });
  }

  bool isComplete() {
    return cycleType.isNotEmpty && cycleType.isNotEmpty && quota > 0.0;
  }

  void changeCycleType(int index) {
    String type = cycleList[index].type;
    if (cycleType != type) {
      cycleType = type;
      cycleName = cycleList[index].name;
      update();
    }
  }

  void changeUnitType(int index) {
    String type = unitList[index].type;
    if (unitType != type) {
      unitType = type;
      unitName = unitList[index].name;
      update();
    }
  }

  void initData() {
    cycleList.add(Cycle("ONCE", "次"));
    cycleList.add(Cycle("DAY", "天"));
    cycleList.add(Cycle("WEEK", "周"));
    cycleList.add(Cycle("MONTH", "月"));
    cycleList.add(Cycle("YEAR", "年"));

    unitList.add(Unit("YUAN", "元"));
    unitList.add(Unit("LITRE", "升"));
  }
}

class Cycle {
  String type;
  String name;

  Cycle(this.type, this.name);
}

class Unit {
  String type;
  String name;

  Unit(this.type, this.name);
}
